package tt.dz.egobus.servicemanager.cycle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import tt.dz.egobus.servicemanager.core.exception.BusinessException;
import tt.dz.egobus.servicemanager.core.task.DynamicTask;
import tt.dz.egobus.servicemanager.core.task.DynamicTaskManager;
import tt.dz.egobus.servicemanager.service.DynamicTaskService;

import java.util.List;

/**
 * @author Anson
 * @date 17-8-4
 * @name 动态定时任务从存储结构中初始化
 * @since 1.0.6
 */
public class AppTaskInitCycleProcessor implements AppCycleProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(AppTaskInitCycleProcessor.class);

    private final DynamicTaskManager dynamicTaskManager;

    private final ApplicationContext applicationContext;

    private DynamicTaskService dynamicTaskService;

    private boolean isProcessor = false;

    public AppTaskInitCycleProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        if (this.applicationContext != null) {
            this.dynamicTaskManager = this.applicationContext.getBean(DynamicTaskManager.class);
            this.dynamicTaskService = this.applicationContext.getBean(
                    "redisDynamicTaskMapService", DynamicTaskService.class);
        } else {
            dynamicTaskManager = null;
            dynamicTaskService = null;
        }
    }

    @Override
    public boolean isProcessor() {
        return this.isProcessor;
    }

    @Override
    public boolean processorInit() throws BusinessException {
        if (dynamicTaskManager != null && this.dynamicTaskService != null) {
            List<DynamicTask> tasks = dynamicTaskService.getCurLiveDynamicTask();
            LOGGER.info("当前存在的动态定时任务个数,dynamicTask.length={}",tasks.size());
            if (!tasks.isEmpty()) {
                for (DynamicTask task : tasks) {
                    this.dynamicTaskManager.addJob(task);
                }
            }
        }
        isProcessor = true;
        return isProcessor;
    }

    @Override
    public boolean processorDestroyed() throws BusinessException {
        return true;
    }
}
